use std::cell::RefCell;
use std::rc::Weak;
use std::rc::Rc;

/// 树结构
#[derive(Debug)]
pub struct Node {
    value: u32,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

pub fn tree_node_test() {
    let leaf_48 = Rc::new(Node {
        value: 48,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });
    let leaf_16 = Rc::new(Node {
        value: 16,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });
    let leaf_8 = Rc::new(Node {
        value: 8,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });
    let branch = Rc::new(Node {
        value: 32,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![Rc::clone(&leaf_8), Rc::clone(&leaf_16), Rc::clone(&leaf_48)]),
    });

    *leaf_48.parent.borrow_mut() = Rc::downgrade(&branch);
    *leaf_16.parent.borrow_mut() = Rc::downgrade(&branch);
    *leaf_8.parent.borrow_mut() = Rc::downgrade(&branch);

    println!("leaf_48 reference num is {}", Rc::strong_count(&leaf_48));
    println!("leaf_16 reference num is {}", Rc::strong_count(&leaf_16));
    println!("branch reference num is {}", Rc::weak_count(&branch));

    for children in branch.children.borrow().iter() {
        println!("children is {}", children.value);
    }
    println!("finish!");
}